package com.atguigu.gmall.user.controller;


import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.util.IpUtil;
import com.atguigu.gmall.model.user.LoginVo;
import com.atguigu.gmall.model.user.UserInfo;
import com.atguigu.gmall.user.service.UserInfoService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Generated;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Api(tags = "用户登录管理")
@RestController
@RequestMapping("/api/user/passport")
public class PassportApiController {
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 登录方法
     *
     * @param loginVo
     * @return
     */
    @PostMapping("/login")
    public Result login(@RequestBody LoginVo loginVo, HttpServletRequest request) {
        //根据用户输入的信息去查找用户信息
        UserInfo userInfo = userInfoService.login(loginVo);
        if (userInfo != null) {
            //生成随机token
            String token = UUID.randomUUID().toString();
            //封装返回给前端的数据
            //  创建一个map 集合
            Map<String, Object> map = new HashMap<>();
            map.put("token", token);
            map.put("nickName", userInfo.getNickName());
            //创建缓存key
            String loginKey = RedisConst.USER_LOGIN_KEY_PREFIX + token;
            //创建缓存的value
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("userId", userInfo.getId().toString());
            jsonObject.put("ip", IpUtil.getIpAddress(request));
            //放入缓存中
            redisTemplate.opsForValue().set(loginKey, jsonObject, RedisConst.USERKEY_TIMEOUT, TimeUnit.SECONDS);
            return Result.ok(map);
        } else {
            return Result.fail().message("登陆失败");
        }
    }

    @GetMapping("logout")
    public Result logout(HttpServletRequest request) {
        //获取token
        String token = request.getHeader("token");
        //获取缓存key
        String loginKey = RedisConst.USER_LOGIN_KEY_PREFIX + token;
        //删除缓存
        redisTemplate.delete(loginKey);
        return Result.ok();
    }
}
